<?php

namespace app\admin\model\information;

use think\Db;
use think\Model;
//use traits\model\SoftDelete;
use app\admin\model\information\Inventory;

class Shelves extends Model
{

    //use SoftDelete;

    

    // 表名
    protected $name = 'shelves';
    
    // 自动写入时间戳字段
    //protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'type_text',
        'switch_text',
        'source_text',
        'qrcode',
        'qrcodeval',
        'qrcode_pre',
        'inventory',
        'inv_class_name',
        'warehouse_name'
    ];

    /**
     * 新增前自动生成编码
     */
    protected static function init()
    {
        Shelves::event('before_insert', function ($user) {
            $first = db('warehouse')->where('id',$user->warehouse_id)->value('number');
            $code='';
            if($user->type_text=="库区"){
                $number_str = db('shelves')->where(['type'=>1,'warehouse_id'=>$user->warehouse_id])->order('id','desc')->value('number');
                $id = intval(substr($number_str, 4));
                $code = $first.'A'.self::isAddZero($id+1);
            }if($user->type_text=="货架"){
                $code = $first.'B'.self::isAddZero($user->row_number).self::isAddZero($user->column_number).self::isAddZero($user->layers_number);
            }if($user->type_text=="托盘"){
                $num = db('shelves')->where(['type'=>3])->count('id')+1;
                $code = '0'.self::isAddZero($num);
            }
            $user->number=$code;
        });
    }

    /**
     * 判断是否需要加0
     * @param $num
     * @return int|null|string
     */

    public static function isAddZero($num)
    {
        $re = null;
        $num = is_string($num)?intval($num):$num;
        if($num<10) $re = '0'.$num;
        else  $re =$num;
       return $re;
    }

    
    public function getTypeList()
    {
        return ['1' => __('Type 1'), '2' => __('Type 2'),'3' => __('Type 3')];
    }

    public function getSwitchList()
    {
        return ['0' => __('Switch 0'),'1' => __('Switch 1')];
    }

    public function getSourceList()
    {
        return ['1' => __('Source 1'), ' 2' => __('Source  2')];
    }
    
    public function getIfemptyList()
    {
        return ['0' => __('Empty 0'), '1' => __('Empty 1')];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getSwitchTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['switch']) ? $data['switch'] : '');
        $list = $this->getSwitchList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getSourceTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['source']) ? $data['source'] : '');
        $list = $this->getSourceList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    //追加二维码前缀
    public function getQrcodePreAttr($value, $data)
    {
        $domain = request()->domain();
        $pre = 'KQ';
        if($data['type']==2){
            $pre = 'HJ';
        }
        if($data['type']==3){
            $pre = 'TP';
        }
        return $pre;
    }

    //追加二维码
    public function getQrcodeAttr($value, $data)
    {
        $domain = request()->domain();
        //$data['qrcode']=$domain.'/index.php/qrcode/build?text='."编码为:".$data['number'].($data['type']==2? '|第'.$data['column_number'].'列,第'.$data['row_number'].'行,第'.$data['layers_number'].'层':'');
        $pre = $this->getQrcodePreAttr($value,$data);
        
        $data['qrcode']=$domain.'/index.php/qrcode/build?text='.$pre.$data['number'];
            //$v['address']=$v['type']==2?'第'.$v['column_number'].'列,第'.$v['row_number'].'行,第'.$v['layers_number'].'层':'';
        return $data['qrcode'];
    }

    //追加二维码val
    public function getQrcodevalAttr($value, $data)
    {
        $domain = request()->domain();
        //$data['qrcode']=$domain.'/index.php/qrcode/build?text='."编码为:".$data['number'].($data['type']==2? '|第'.$data['column_number'].'列,第'.$data['row_number'].'行,第'.$data['layers_number'].'层':'');
        $pre = $this->getQrcodePreAttr($value,$data);
        
        $data['qrcode']=$pre.$data['number'];
            //$v['address']=$v['type']==2?'第'.$v['column_number'].'列,第'.$v['row_number'].'行,第'.$v['layers_number'].'层':'';
        return $data['qrcode'];
    }

    //返回物料
    public function getInventoryAttr($value, $data)
    {
        if(isset($data['inv_ids'])&&$data['inv_ids']){
            return Inventory::get($data['inv_ids']);
        }
    }

    public function getWarehouseNameAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['warehouse_id']) ? $data['warehouse_id'] : '');
        return db('warehouse')->where('id',$value)->value('name');
    }

    public  function getTreeData($warehouse_id = ''){
        $where['warehouse_id'] = 2;
        if($warehouse_id){
            $where['warehouse_id'] =$warehouse_id;
        }
        $list = Db::name('shelves')->field('id,name,column_number,layers_number,row_number,type')
            ->where('deletetime is NULL and switch=1 ')
            ->where($where)
            ->order('row_number desc,column_number desc ,layers_number desc')
            ->select();
        $typeRack = [];

        $treeData[] = [
            'id' => 999997,
            'name' => '托盘',
            'pid' => 0,
        ];
        $treeData[] = [
            'id' => 999998,
            'name' => '库区',
            'pid' => 0,
        ];
        $treeData[] = [
            'id' => 999999,
            'name' => '货架',
            'pid' => 0,
        ];
        foreach ($list  as $k=>$v){

            $rowNumber     = $this->isAddZero($v['row_number']);
            $columnNumber  = $this->isAddZero($v['column_number']);
            $layersNumber  = $this->isAddZero($v['layers_number']);


            if($v['type']==1){   //库区
                $treeData[] = [
                    'id' => 999998-$v['id'],
                    'name' => $v['name'],
                    'pid' => 999998,
                ];
            }else if($v['type']==2){             //货架
                if(in_array($rowNumber,array_keys($typeRack))){

                    if(in_array($columnNumber,array_keys($typeRack[$rowNumber]))){
                        if(!in_array($layersNumber,$typeRack[$rowNumber][$columnNumber])){

                            $typeRack[$rowNumber][$columnNumber][] = $layersNumber;
                            $treeData[] = [
                                'id' => $rowNumber.$columnNumber.$layersNumber,
                                'name' => '第'.$layersNumber.'层',
                                'pid' => $rowNumber.$columnNumber,
                            ];
                        }
                    }else{
                        $typeRack[$rowNumber][$columnNumber][] = $layersNumber;
                        $treeData[] = [
                                'id' => $rowNumber.$columnNumber,
                                'name' => '第'.$columnNumber.'列',
                                'pid' => $rowNumber,
                            ];
                        $treeData[] = [
                            'id' => $rowNumber.$columnNumber.$layersNumber,
                            'name' => '第'.$layersNumber.'层',
                            'pid' => $rowNumber.$columnNumber,
                        ];
                    }

                }else{
                    $typeRack[$rowNumber][$columnNumber][] = $layersNumber;

                    $treeData[] = [
                        'id' => $rowNumber,
                        'name' => '第'.$rowNumber.'行',
                        'pid' => 999999,
                    ];
                    $treeData[] = [
                        'id' => $rowNumber.$columnNumber,
                        'name' => '第'.$columnNumber.'列',
                        'pid' => $rowNumber,
                    ];
                    $treeData[] = [
                        'id' => $rowNumber.$columnNumber.$layersNumber,
                        'name' => '第'.$layersNumber.'层',
                        'pid' => $rowNumber.$columnNumber,
                    ];

                }
            }else if($v['type']==3){//托盘
                $treeData[] = [
                    'id' => 999997-$v['id'],
                    'name' => $v['name'],
                    'pid' => 999997,
                ];
            }
        }

        return $treeData;
    }

    /*
     * 判断货架、库区的属性，如果是代管仓的，只能直入，直出，不回写到u8
     *   */
    public static function checkWhtypeById($shelves_id,$to_shelves_id = 0,$order_type,$return_flag = 'exception'){
        if(!$shelves_id||!$order_type){
            if($return_flag=='exception'){
                exception('判断货架、库区的属性，参数错误');
            }else{
                return false;
            }
        }
        
        $shelves = self::get($shelves_id);
        if($to_shelves_id){
            $to_shelves = self::get($to_shelves_id);
        }
        if($order_type == 8){//8调拨   2个货架或库区，属性都是代管仓的可以调拨过去
            if($shelves&&$to_shelves){
                //如果2个货架中，有一个是代管，另一个不是则抛出异常
                if(($shelves->wh_type==2&&$to_shelves->wh_type!=2)||($shelves->wh_type!=2&&$to_shelves->wh_type==2)){
                    if($return_flag=='exception'){
                        exception('调拨单中存在路径属性不一致，只能代管仓调拨入代管仓');
                    }else{
                        return false;
                    }
                }
            }else{
                if($return_flag=='exception'){
                    exception('调拨单传入参数异常');
                }else{
                    return false;
                }
            }
        }else{
            //7领料退回   10直接上架    11直接领料
            $order_type_arr = [7,10,11];//允许进入代管仓的单据类型
            if($shelves->wh_type==2){
                //代管仓,不在上面3种单据内的
                if(!in_array($order_type, $order_type_arr)){
                    if($return_flag=='exception'){
                        exception("路径[{$shelves->name}]属性是代管仓,不允许本次操作");
                    }else{
                        return false;
                    }
                }
            }
        }
        return true;
    }

    //得到转换后的erp_warehouse_id
    public static function getErpWarehouseId($v = [],$str = 'shelves_id'){
        if(!$v){
            return false;
        }

        if($str == 'shelves_id'&&isset($v['shelves_id'])){
            //产品入库的单，还是入到，湖南账套，成品仓（货架目前设置指向广东味业）
            if(isset($v['order_list'])&&$v['order_list']==14){
                return $v['warehouse_id'];
            }else{
                $shelves = self::get($v['shelves_id']);
                if($shelves){
                    $erp_warehouse_id =  $shelves->erp_warehouse_id;
                    //目标erp转换仓库id不为空
                    if($erp_warehouse_id&&$str=='shelves_id'){
                        return $erp_warehouse_id;
                    }
                }
            }
        }
        
        if($str == 'shelves_change_id' && isset($v['shelves_change_id'])){
            $shelves = self::get($v['shelves_change_id']);
            if($shelves){
                $erp_warehouse_id =  $shelves->erp_warehouse_id;
                //目标erp转换仓库id不为空
                if($erp_warehouse_id&&$str=='shelves_change_id'){
                    return $erp_warehouse_id;
                }
            }
        }
        return false;
    }

    //得到货架对应的账套，默认湖南010
    public static function getErpAccNum($shelves_id = 0,$order_type){
        if(!$shelves_id||$order_type==14){//产品入库14，到湖南账套
            return '010';
        }

        $acc = self::get($shelves_id);
        return  $acc->erp_acc_id;
    }
}
